package utils;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import entities.GuestUser;
import hotel.jpa.IJpaCtrl;
import hotel.jpa.UserJpaCtrl;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author viklju
 */
@FacesValidator(value = "myEmailValidator")
public class MyEmailValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value)
            throws ValidatorException {

        //Get the input from user
        String email = (String) value;

        //Create correct email reg-ex
        String MatchEmailPattern = "^[a-z0-9_+-]+(.[a-z0-9_+-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*.([a-z]{2,4})$";

        //Check if email is unique comparable with the database
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hotel_pu");
        IJpaCtrl userCtrl = new UserJpaCtrl(null, emf);
        
        List<GuestUser> users = userCtrl.findEntities();
        
        boolean unique = false;
        for(GuestUser u : users){
            if(u.getEmail().compareTo(email) == 0){
                unique = true;
            }
        }

        //Throw exception if the email isn't valid
        if (!email.matches(MatchEmailPattern)) {
            ((UIInput) component).setValid(false);
            throw new ValidatorException(new FacesMessage("Invalid Email"));
        }
        
        //Throw exception if the email already exist in the database
        if (unique) {
            ((UIInput) component).setValid(false);
            throw new ValidatorException(new FacesMessage("Email already exists"));
        }

    }
}
